package com.qishanor.framework.mybatis.datascope;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qishanor.framework.constant.CacheConstant;
import com.qishanor.framework.mybatis.datascope.DataScopeHandle;
import com.qishanor.framework.mybatis.datascope.DataScopeTypeEnum;
import com.qishanor.system.mapper.SysRoleMapper;
import com.qishanor.system.model.SysDeptRelation;
import com.qishanor.system.model.SysRole;
import com.qishanor.system.model.SysUser;
import com.qishanor.system.service.SysDeptRelationService;
import com.qishanor.system.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 默认data scope 判断处理器
 */
public class ZeusDefaultDatascopeHandle implements DataScopeHandle {

	@Autowired
	@Lazy
	private SysRoleMapper sysRoleMapper;

	@Autowired
	@Lazy
	private SysDeptRelationService sysDeptRelationService;

	/**
	 * 计算用户数据权限
	 * @param deptList
	 * @return
	 */
	@Override
	public Boolean calcScope(List<Integer> deptList) {
		SysUser user=StpUtil.getSession().getModel(CacheConstant.USER_DETAIL,SysUser.class);
		List<Integer> roleIdList = (List<Integer>)StpUtil.getSession().get(CacheConstant.ROLE_DETAIL);
		// 当前用户的角色为空
		if (CollectionUtil.isEmpty(roleIdList)) {
			return false;
		}
		SysRole role = sysRoleMapper.selectList(Wrappers.lambdaQuery(SysRole.class).in(SysRole::getId,roleIdList))
				.stream().min(Comparator.comparingInt(SysRole::getDsType)).orElse(null);
		// 角色有可能已经删除了
		if (role == null) {
			return false;
		}
		Integer dsType = role.getDsType();
		// 查询全部
		if (DataScopeTypeEnum.ALL.getType() == dsType) {
			return true;
		}
		// 自定义
		if (DataScopeTypeEnum.CUSTOM.getType() == dsType && StrUtil.isNotBlank(role.getDsScope())) {
			String dsScope = role.getDsScope();
			deptList.addAll(
					Arrays.stream(dsScope.split(StrUtil.COMMA)).map(Integer::parseInt).collect(Collectors.toList()));
		}
		// 查询本级及其下级
		if (DataScopeTypeEnum.OWN_CHILD_LEVEL.getType() == dsType) {
			List<Integer> deptIdList =sysDeptRelationService.list(Wrappers.lambdaQuery(SysDeptRelation.class).eq(SysDeptRelation::getAncestor, user.getDeptId()))
					.stream().map(SysDeptRelation::getDescendant).collect(Collectors.toList());
			deptList.addAll(deptIdList);
		}
		// 只查询本级
		if (DataScopeTypeEnum.OWN_LEVEL.getType() == dsType) {
			deptList.add(user.getDeptId());
		}
		return false;
	}

}
